package com.banggood.upms.service.impl;

import com.banggood.silk.web.api.exception.SkbException;
import com.banggood.upms.bean.exception.ExceptionEnum;
import com.banggood.upms.bean.po.User;
import com.banggood.upms.common.util.PasswordUtil;
import com.banggood.upms.dao.UserDao;
import com.banggood.upms.service.UserScopeService;
import com.banggood.upms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author XuChuangFeng
 */
@Service
@Transactional(rollbackFor = SkbException.class)
public class UserServiceImpl extends BaseServiceImpl<User, UserDao> implements UserService {

    @Override
    @Autowired
    public void setDao(UserDao dao) {
        super.dao = dao;
    }

    @Autowired
    private UserScopeService userScopeService;

    @Override
    public int insert(User user) throws Exception {
        if(this.isAccountNameDuplicated(user.getAccountName())) {
            throw new SkbException(ExceptionEnum.DUPLICATED_ACCOUNT_NAME.getCode(), ExceptionEnum.DUPLICATED_ACCOUNT_NAME.getMessage());
        }
        if (!this.userScopeService.ifScopeKeyExist(user.getScope())) {
            throw new SkbException(ExceptionEnum.INVALIDATE_USER_SCOPE.getCode(), ExceptionEnum.INVALIDATE_USER_SCOPE.getMessage());
        }
        user.setUserId(commonComponent.generateId());
        user.setEncryptSalt(PasswordUtil.generateSalt());
        return dao.insert(user);
    }

    @Override
    public boolean isAccountNameDuplicated(String accountName) {
        return dao.selectByAccount(accountName) != null;
    }
}
